//
//  proDetialViewController.m
//  LazyCat
//
//  Created by rocky on 16/2/20.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "proDetialViewController.h"
#import "ProductDetailImgCell.h"
#import "MJRefresh.h"
#import "ProDetailMessageCell.h"
#import "ProDetailTagCell.h"
#import "SFTag.h"
#import "SFTagView.h"
#import "YYText.h"
#import "AddProductViewController.h" //编辑商品
#import "AddProduct.h"

@interface proDetialViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UIWebViewDelegate,UIAlertViewDelegate>

{
    UITableView *pdTableView;
    UIView *bottomV;
    NSDictionary *dataDic;
    NSString *_shareUrl;//分享
    AddProduct *aLcProducct;
    
    UIButton *toTopBt;
    UIView *_hasBeenBottomV;
    
    //底部5个控件()
    UIButton *btn1_edit;
    UIButton *btn2_public;
    UIButton *btn3_recommend;
    UIButton *btn4_share;
    UIButton *btn5_delete;
    
    BOOL _hasSpec; //是否有多规格
    NSString *_selectedSpec;
    NSString *_selectedSpecid;
    NSString *_selectedProp;
    
    NSInteger _currentSpecIndex;//多规格用来判断当前规格是第几个
    BOOL _isSuccess;
    
    
}
@property(strong,nonatomic)UIScrollView *scrollV;
@property(strong,nonatomic)UIWebView *webV;
/** "商品详情View" */
@property(nonatomic,strong)UIView *detailTextView;
/** tagCell左边name数组 */
@property(nonatomic,strong)NSMutableArray *leftNameArrs;
/** tagCell标签数组的数组 */
@property(nonatomic,strong)NSMutableArray *tagArrs;
/** 多规格id数组 */
@property(nonatomic,strong)NSMutableArray *specIdArrs;
/** 多规格img路径数组 */
@property(nonatomic,strong)NSMutableArray *specImgArrs;
@property(nonatomic,strong)NSMutableArray *selectedTagArrs;

@end

@implementation proDetialViewController
#pragma mark ---- get

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refreshToTopView];
    if (_isSuccess) { //编辑界面修改数据成功后过来要刷新数据
        [self getDataById];
    }
}
-(UIScrollView *)scrollV
{
    if (_scrollV == nil)
    {
        _scrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-114)];
        _scrollV.contentSize = CGSizeMake(ScreenWidth, (ScreenHeight-114)* 2);
        //设置分页效果
        _scrollV.pagingEnabled = YES;
        //禁用滚动
        _scrollV.scrollEnabled = NO;
    }
    return _scrollV;
}

-(UIWebView *)webV
{
    if (_webV == nil)
    {
        _webV = [[UIWebView alloc]initWithFrame:CGRectMake(0, ScreenHeight+45, ScreenWidth, ScreenHeight-159)];
        _webV.delegate = self;
        _webV.scrollView.delegate = self;
        _webV.backgroundColor = BackColor;
        _webV.scalesPageToFit = YES;
    }
    return _webV;
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    
    if (pdTableView == scrollView) {
        //确保pdTableView能完全滑动
        CGFloat margin = pdTableView.contentSize.height - (ScreenHeight-114);
        if (pdTableView.contentOffset.y > (margin+25) && aLcProducct.desc_url.length > 0) {
            __weak typeof(self) vv = self;
            
            [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                vv.scrollV.contentOffset = CGPointMake(0, ScreenHeight);
            } completion:^(BOOL finished) {
                //结束加载
                [pdTableView.footer endRefreshing];
            }];
            
        }
    }
    
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (_scrollV.contentOffset.y > ScreenHeight-114 ) {
        toTopBt.hidden = NO;
        [self.view bringSubviewToFront:toTopBt];
    }else{
        toTopBt.hidden = YES;
    }
    
    if (scrollView == _webV.scrollView) {
        if (_webV.scrollView.contentOffset.y >= _webV.scrollView.contentSize.height - (ScreenHeight-114)+70) { //70=20+50
            _hasBeenBottomV.hidden = NO;
        }else{
            _hasBeenBottomV.hidden = YES;
            
        }
    }
    
}


#pragma mark --- webV上面的标题“图文详情”
-(void)creeatDeatilTextView
{
    _detailTextView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight, ScreenWidth, 45)];
    _detailTextView.backgroundColor = [UIColor whiteColor];
    [self.scrollV addSubview:_detailTextView];
    
    UILabel *detailTextLB = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth-30, 44)];
    detailTextLB.text = @"图文详情";
    detailTextLB.textColor = MainColor;
    detailTextLB.font = FontSet(13);
    [_detailTextView addSubview:detailTextLB];
    
    UIView *bottomLine = [[UIView alloc]initWithFrame:CGRectMake(0, 44, ScreenWidth, 1)];
    bottomLine.backgroundColor = SetColor(228, 228, 228, 1.0);
    [_detailTextView addSubview:bottomLine];
    
    CGFloat mainColorLineW = [Utils calculateSizeWithText:detailTextLB.text height:44 fontSize:13].width;
    UIView *mainColorLine = [[UIView alloc]initWithFrame:CGRectMake(10, 43, mainColorLineW+10, 2)];
    mainColorLine.backgroundColor = MainColor;
    [_detailTextView addSubview:mainColorLine];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNav:self.pTitle doBack:YES];
    self.view.backgroundColor = BackColor;
    _leftNameArrs = [NSMutableArray array];
    _tagArrs = [NSMutableArray array];
    _hasSpec = NO;
    _specIdArrs = [NSMutableArray array];
    _specImgArrs = [NSMutableArray array];
    _selectedTagArrs = [NSMutableArray array];
    _currentSpecIndex = 0;
    _selectedProp = @"";
    _isSuccess = NO;
    
    aLcProducct = [[AddProduct alloc]init];
    
    toTopBt = [UIButton buttonWithType:UIButtonTypeCustom];
    toTopBt.frame = CGRectMake(ScreenWidth-44-10, ScreenHeight-50-20-44, 44, 44);
    [toTopBt setImage:[UIImage imageNamed:@"totop.png"] forState:UIControlStateNormal];
    [self.view addSubview:toTopBt];
    toTopBt.hidden = YES;
    [toTopBt addTarget:self action:@selector(toTop) forControlEvents:UIControlEventTouchUpInside];
    
    [self creatMainView];
    [self getDataById];
    
    if (kNetworkNotReachability) { // 没网
        self.baseNetView.hidden = NO;
        pdTableView.hidden = YES;
    }else{
        pdTableView.hidden = NO;
        self.baseNetView.hidden = YES;
    }
    //04--26
    [self.view addSubview:self.scrollV];
    [self.scrollV addSubview:pdTableView];
    [self creeatDeatilTextView];
    [self.scrollV addSubview:self.webV];
    self.scrollV.delegate = self;
  
    [self setupHasBeenBottom];
#pragma mark -- 下拉返回上一页
    //设置UIWebView 有下拉操作
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshToTopView)];
    header.arrowView.hidden = YES;
    header.arrowView.image = nil;
    header.backgroundColor = BackColor;
    // 设置header
    self.webV.scrollView.header = header;
}
#pragma mark --- 设置“已经到底啦”view
-(void)setupHasBeenBottom
{
    _hasBeenBottomV = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-50-30, ScreenWidth, 30)];
    [self.view addSubview:_hasBeenBottomV];
    
    UILabel *headLabel = [[UILabel alloc]init];
    headLabel.text = @"已经到底啦~";
    headLabel.font = [UIFont systemFontOfSize:11];
    CGSize size = [headLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:headLabel.font,NSFontAttributeName, nil]];
    headLabel.frame = CGRectMake((ScreenWidth - size.width)/2, 0, size.width, 30);
    headLabel.textColor = SetColor(153, 153, 153, 1);
    headLabel.textAlignment = NSTextAlignmentCenter;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(headLabel.left - 80 -10,15, 80, 1)];
    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(headLabel.right + 10,15, 80, 1)];
    lineView.backgroundColor = SetColor(204, 204, 204, 0.6);
    lineView2.backgroundColor = SetColor(204, 204, 204, 0.6);
    
    [_hasBeenBottomV addSubview:headLabel];
    [_hasBeenBottomV addSubview:lineView];
    [_hasBeenBottomV addSubview:lineView2];
    _hasBeenBottomV.hidden = YES;
}

- (void)refreshToTopView {
    [UIView animateWithDuration:0.5 animations:^{
        pdTableView.contentOffset = CGPointMake(0, 0);
        self.scrollV.contentOffset = CGPointMake(0, 0);
    }];
    [self.webV.scrollView.header endRefreshing];
    //要在结束刷新后再隐藏
    _hasBeenBottomV.hidden = YES;
}
//"返回顶部"按钮点击事件
-(void)toTop{
    
    [UIView animateWithDuration:0.1 animations:^{
        [_scrollV setContentOffset:CGPointMake(0, 0)];
        [pdTableView setContentOffset:CGPointMake(0, 0)];
      
    } completion:^(BOOL finished) {
        toTopBt.hidden = YES;
        _hasBeenBottomV.hidden = YES;
    }];
    
}
-(void)setupArrsData:(AddProduct *)aPro
{
    
    [_leftNameArrs removeAllObjects];
    [_tagArrs removeAllObjects];
    [_specIdArrs removeAllObjects];
    [_specImgArrs removeAllObjects];
    [_selectedTagArrs removeAllObjects];
    
    //先走一遍，判断是不是多规格，其中有一个大于等于2个标签，其他的如果有一个也要显示
    //是否有“可选规格”
    NSInteger propKexuan = 0;
    if (aPro.productspec.count > 1) {
        propKexuan++;
    }
    
    for (int i = 0; i<aPro.productprop.count; i++) {
        LCProductProp *aprop = [[LCProductProp alloc]init];
        aprop = aPro.productprop[i];
        if (aprop.propertyvalue.length > 0 && [aprop.propertyvalue rangeOfString:@","].location != NSNotFound) {
            NSArray *props = [aprop.propertyvalue componentsSeparatedByString:@","];
            if (props.count > 1) {
                propKexuan++;
            }
        }
    }
    //在取得propKexuan的数量后，如果大于0，就所有的都加
    NSString *nameGuige = aPro.property;
    //规格
    NSArray *specArrs = aPro.productspec;
    NSMutableArray *specTags = [NSMutableArray array];
    for (int i = 0; i<specArrs.count; i++) {
        LCProductSpec *spec = [[LCProductSpec alloc]init];
        spec = specArrs[i];
        [specTags addObject:[Utils isNullToString:spec.specname]];
        [_specIdArrs addObject:[Utils isNullToString:spec.specid]];
        [_specImgArrs addObject:[Utils isNullToString:spec.mainimage]];
    }
    
    //propKexuan > 0大于一切
    if (propKexuan > 0) {
        if (specTags.count > 1) {
            _hasSpec = YES; //有多规格
        }
        [_leftNameArrs addObject:nameGuige];
        [_selectedTagArrs addObject:@"-11"];
        [_tagArrs addObject:specTags];
    }
    
    //没有多规格设置默认的【其实就是第一个】
    if (_specIdArrs.count > 0) {
        _selectedSpecid = _specIdArrs[0];
    }
    
    //属性
    NSArray *propArrs = aPro.productprop;
    for (int i = 0; i<propArrs.count; i++) {
        LCProductProp *prop = [[LCProductProp alloc]init];
        prop = propArrs[i];
        NSString *propName = [Utils isNullToString:prop.propertyname];
        NSString *propValue = [Utils isNullToString:prop.propertyvalue];
        if (propKexuan > 0) {
            NSMutableArray *props = [NSMutableArray array];
            if (propValue.length > 0) {
                if ([propValue rangeOfString:@","].location != NSNotFound) {
                    props = (NSMutableArray *)[propValue componentsSeparatedByString:@","];
                }else{
                    [props addObject:propValue];
                }
                if (props.count > 0) {
                    [_leftNameArrs addObject:propName];
                    [_selectedTagArrs addObject:@"-11"];
                    [_tagArrs addObject:props];
                }
            }
        }
    }

}
#pragma mark --- 根据userproductid获取商品信息
-(void)getDataById
{
    [MBProgressHUD showLCHud:self.view];
    if (kNetworkNotReachability) { // 没有网
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share] showWithMessLC:@"网络不给力,请检查网络"];
        return;
    }else{
        
        NSString *editUrl = [NSString stringWithFormat:GetProductEditDataUrl,self.pId,[AppData share].username,@"1"];
        [NTNetUtil sendRequestWithUrl:editUrl requestName:@"getEditData" method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *resultDict = (NSDictionary *)networkRequest.responseData;
            LCLog(@"111根据userproductid获取商品信息--%@\n-%@---\n%@",resultDict,editUrl,aLcProducct);
            if (error) {
                [MBProgressHUD hideLCHud:self.view];
                [[MessShowView share]showWithMessLC:@"没有该商品信息" login:NO];
                return ;
                
            }else{
                NSDictionary *dic = (NSDictionary *)networkRequest.responseData;
                aLcProducct = [AddProduct mj_objectWithKeyValues:dic];
                if ([aLcProducct.m isEqualToString:@"success"]) {
                    [MBProgressHUD hideLCHud:self.view];
                    [self setupArrsData:aLcProducct];
                    //有图文详情时
                    if (aLcProducct.desc_url.length > 0) {
                        [_webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:aLcProducct.desc_url]]];
                    }
                    //设置底部按钮显示
                    if ([aLcProducct.ispublic isEqualToString:@"1"]) { //上架状态
                        [btn2_public setTitle:@"下架" forState:UIControlStateNormal];
                        [btn2_public setTitle:@"下架" forState:UIControlStateHighlighted];
                    }else{
                        [btn2_public setTitle:@"上架" forState:UIControlStateNormal];
                        [btn2_public setTitle:@"上架" forState:UIControlStateHighlighted];
                    }
                    if ([aLcProducct.ishot isEqualToString:@"1"]) { //推荐状态
                        [btn3_recommend setTitle:@"已推荐" forState:UIControlStateNormal];
                        [btn3_recommend setTitle:@"已推荐" forState:UIControlStateHighlighted];
                        [btn3_recommend setTitleColor:SetColorRGBValue(0xff6600, 1.0) forState:UIControlStateNormal];
                        [btn3_recommend setTitleColor:SetColorRGBValue(0xff6600, 1.0) forState:UIControlStateHighlighted];
                        
                    }else{
                        [btn3_recommend setTitle:@"推荐" forState:UIControlStateNormal];
                        [btn3_recommend setTitle:@"推荐" forState:UIControlStateHighlighted];
                        [btn3_recommend setTitleColor:SetColorRGBValue(0x333333, 1.0) forState:UIControlStateNormal];
                        [btn3_recommend setTitleColor:SetColorRGBValue(0x333333, 1.0) forState:UIControlStateHighlighted];
                    }
                }else{
                    [MBProgressHUD hideLCHud:self.view];
                    [[MessShowView share]showWithMessLC:aLcProducct.m login:NO];
                }
                [pdTableView reloadData];
            }
        }];
        
    }
    
}


#pragma mark -- 创建视图
-(void)creatMainView {
    pdTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-114) style:UITableViewStylePlain];
    pdTableView.backgroundColor = [UIColor clearColor];
    pdTableView.delegate = self;
    pdTableView.dataSource = self;
    pdTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self creatBottomVUI];
}
-(void)creatBottomVUI
{
    bottomV = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-50, ScreenWidth, 50)];
    bottomV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomV];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line.backgroundColor = SetColorRGBValue(0xe0e0e0, 1.0);
    line.alpha = 0.5;
    [bottomV addSubview:line];
    
    CGFloat bottomBtW = (ScreenWidth-4)/5;
     for (int i=0; i<5; i++) {
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        [bottomV addSubview:bt];
        bt.tag = 1230+i;
        CGFloat btX = (bottomBtW+1)*i;
        bt.frame = CGRectMake(btX, 1, bottomBtW, 49);
         [bt setTitleColor:SetColorRGBValue(0x333333, 1.0) forState:UIControlStateNormal];
         [bt setTitleColor:SetColorRGBValue(0x333333, 1.0) forState:UIControlStateHighlighted];
         bt.titleLabel.font = FontSet(14);
        [bt addTarget:self action:@selector(bottomBTClicked:) forControlEvents:UIControlEventTouchUpInside];
        NSString *btTitle;
        if (i==0) {
            btn1_edit = bt;
            btTitle = @"编辑";
        }else if (i==1){
            btn2_public = bt;
            btTitle = @"下架";
        }else if (i==2){
            btn3_recommend = bt;
            btTitle = @"推荐";
        }else if (i==3){
            btn4_share = bt;
            btTitle = @"分享";
        }else if (i==4){
            btn5_delete = bt;
            btTitle = @"删除";
        }
         [bt setTitle:btTitle forState:UIControlStateNormal];
         [bt setTitle:btTitle forState:UIControlStateHighlighted];
         
         //竖线
         UIView *rightLine = [[UIView alloc]initWithFrame:CGRectMake(bt.right, 11, 1, 29)];
         rightLine.backgroundColor = SetColorRGBValue(0xe0e0e0, 1.0);
         rightLine.alpha = 0.5;
         [bottomV addSubview:rightLine];
    }
}

-(void)bottomBTClicked:(UIButton *)bt
{
    switch (bt.tag) {
        case 1230: //编辑
        {
            AddProductViewController *editVC = [[AddProductViewController alloc]init];
            editVC.addVCStyle = LCProductStyleEdit;
            editVC.userproductid = aLcProducct.productid;
            [editVC setSaveSuccessBlock:^(BOOL isSuccess) {
                _isSuccess = isSuccess;
            }];
            [self.navigationController pushViewController:editVC animated:YES];
        }
            break;
        case 1231: //上下架（根据ispublic判断相反的展示）
        {
            [self bottomPublicBtnClicked];
        }
            break;
        case 1232: //推荐
        {
            [self bottomRecommendBtnClicked];
        }
            break;
        case 1233://分享
        {
//            [self shareAction];
            [self fenXiangAction];
        }
            break;
        case 1234://删除
        {
            [self bottomDeleteBtnClicked];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark --- 上下架按钮点击事件
-(void)bottomPublicBtnClicked
{
    NSString *kUrl;
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray *arr = [NSMutableArray array];//产品信息
    [arr addObject:aLcProducct.productid];
    [dictionary setValue:arr forKey:@"productids"];
    if ([aLcProducct.ispublic isEqualToString:@"1"]) { //刚好相反
        [dictionary setValue:@"0" forKey:@"ispublic"];
    }else{
        [dictionary setValue:@"1" forKey:@"ispublic"];
    }
    NSError *error = nil;
    //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        NSLog(@"Successfully serialized the dictionary into data.");
        //NSData转换为String
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
    }
    else if ([jsonData length] == 0 &&
             error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }
    //post请求
    kUrl = [NSString stringWithFormat:shangXiaJiaProduct,[AppData share].username,[AppData share].username];
    NSLog(@"%@",kUrl);
    NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
    [dicc setObject:dictionary forKey:@"data"];
    NSLog(@"%@",dicc);
    // 手机型号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    NSString *temUrl = [NSString stringWithFormat:@"%@&terminal=%@&OSVersion=%@",kUrl,iptype,banben];
    // 判断是否签名
    if([temUrl rangeOfString:@"sign2"].location !=NSNotFound)//_roaldSearchText
    {
        // 存在
    }else{
        // 不存在
        temUrl = [NSString stringWithFormat:@"%@&sign2=%@",temUrl,[Utils md5SignStr]];
        
    }
    NSString *lower = [temUrl lowercaseString];
    if ([lower rangeOfString:@"username"].location !=NSNotFound) {
        // 存在
    }else{
        // 不存在
        temUrl = [NSString stringWithFormat:@"%@&Username=%@",temUrl,[AppData share].username];
    }
    temUrl = [temUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSError *error1;
    NSURLResponse *theResponse;
    
    [MBProgressHUD showLCHud:self.view];
    
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:temUrl]];
    NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([dic[@"r"] isEqualToString:@"T"]) {
        [MBProgressHUD hideLCHud:self.view];
        if ([aLcProducct.ispublic isEqualToString:@"1"]) { //上架状态
            [btn2_public setTitle:@"上架" forState:UIControlStateNormal];
            [btn2_public setTitle:@"上架" forState:UIControlStateHighlighted];
            aLcProducct.ispublic = @"0";
            [[MessShowView share]showWithMess:@"下架成功"];
#warning pp
            //下架成功，返回商品列表（可以不拉数据，数组删除当前行，直接刷新）
            
        }else{
            [btn2_public setTitle:@"下架" forState:UIControlStateNormal];
            [btn2_public setTitle:@"下架" forState:UIControlStateHighlighted];
            [[MessShowView share]showWithMess:@"上架成功"];
            aLcProducct.ispublic = @"1";
        }
        
    }else {
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share]showWithMess:dic[@"m"]];
    }

}
#pragma mark --- 推荐按钮点击事件
-(void)bottomRecommendBtnClicked
{
    NSString *kUrl;
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray *arr = [NSMutableArray array];//产品信息
    [arr addObject:aLcProducct.productid];
    [dictionary setValue:arr forKey:@"productids"];
    if ([aLcProducct.ishot isEqualToString:@"1"]) { //刚好相反
        [dictionary setValue:@"0" forKey:@"ishot"];
    }else{
        [dictionary setValue:@"1" forKey:@"ishot"];
    }
    NSLog(@"%@",dictionary);
    NSError *error = nil;
    //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        NSLog(@"Successfully serialized the dictionary into data.");
        //NSData转换为String
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
    }
    else if ([jsonData length] == 0 &&
             error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }
    //post请求
    kUrl = [NSString stringWithFormat:isRecommend,[AppData share].username,[AppData share].username];
    NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
    [dicc setObject:dictionary forKey:@"data"];
    // 手机型号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    NSString *temUrl = [NSString stringWithFormat:@"%@&terminal=%@&OSVersion=%@",kUrl,iptype,banben];
    // 判断是否签名
    if([temUrl rangeOfString:@"sign2"].location !=NSNotFound)//_roaldSearchText
    { // 存在
    }else{ // 不存在
        temUrl = [NSString stringWithFormat:@"%@&sign2=%@",temUrl,[Utils md5SignStr]];
    }
    NSString *lower = [temUrl lowercaseString];
    if ([lower rangeOfString:@"username"].location !=NSNotFound) { // 存在
    }else{ // 不存在
        temUrl = [NSString stringWithFormat:@"%@&Username=%@",temUrl,[AppData share].username];
    }
    //NSLog(@"1----------%@",temUrl);
    temUrl = [temUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"2----------%@",temUrl);
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSError *error1;
    LCLog(@"%@",error1);
    NSURLResponse *theResponse;
    [MBProgressHUD showLCHud:self.view];
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:temUrl]];
    NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([dic[@"r"] isEqualToString:@"T"]) {
        [MBProgressHUD hideLCHud:self.view];
        if ([aLcProducct.ishot isEqualToString:@"1"]) { //推荐状态
            [btn3_recommend setTitle:@"推荐" forState:UIControlStateNormal];
            [btn3_recommend setTitle:@"推荐" forState:UIControlStateHighlighted];
            [btn3_recommend setTitleColor:SetColorRGBValue(0x333333, 1.0) forState:UIControlStateNormal];
            [btn3_recommend setTitleColor:SetColorRGBValue(0x333333, 1.0) forState:UIControlStateHighlighted];
            [[MessShowView share]showWithMess:@"取消推荐"];
            aLcProducct.ishot = @"0";
        }else{
            [btn3_recommend setTitle:@"已推荐" forState:UIControlStateNormal];
            [btn3_recommend setTitle:@"已推荐" forState:UIControlStateHighlighted];
            [btn3_recommend setTitleColor:SetColorRGBValue(0xff6600, 1.0) forState:UIControlStateNormal];
            [btn3_recommend setTitleColor:SetColorRGBValue(0xff6600, 1.0) forState:UIControlStateHighlighted];
            [[MessShowView share]showWithMess:@"已推荐"];
            aLcProducct.ishot = @"1";
        }
    }else {
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share]showWithMess:dic[@"m"]];
    }

}
#pragma mark --- 删除按钮点击事件
-(void)bottomDeleteBtnClicked
{
    UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"确认删除" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
    alertV.tag = 50;
    [alertV show];
}
#pragma mark - 分享点击事件【社长版】
- (void)shareAction {
    NSArray *array = [_shareUrl componentsSeparatedByString:@"?"];
    NSString *ur = array[0];
    NSString *url = [NSString stringWithFormat:@"%@?sharedUser=%@",ur,[AppData share].username];
    [[ShareView share] showMess:[NSString stringWithFormat:@"%@%@",dataDic[@"name"],url] withImgUrl:dataDic[@"img"] url:url];
}
// 分享
-(void)fenXiangAction {
    NSString *url = [NSString stringWithFormat:@"%@/LCat/Product-%@?appname=lanmao&plat=ios&username=%@&iszhanggui=1&sign2=%@",BaseUrl,aLcProducct.productid,[AppData share].username,[Utils md5SignStr]];
    [[ShareView share] showMess:[NSString stringWithFormat:@"%@%@",aLcProducct.productname,url] withImgUrl:aLcProducct.mainimage url:url];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{

    if (section == 0) {
        if (_tagArrs.count > 0) {
            UIView *footerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 5)];
            footerV.backgroundColor = BackColor;
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
            line.backgroundColor = SetColorRGBValue(0xe0e0e0, 0.5);
            [footerV addSubview:line];
            return footerV;
        }
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        if (_tagArrs.count > 0) {
            return 5;
        }
    }
    return 0.0001;
}
#pragma mark -- uitableViewdataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else{
        NSInteger rows = 0;
        if (aLcProducct.desc_url.length == 0) {
            rows = 1;  //无图文详情[商品信息]
        }else{
            rows = 2; //有图文详情【商品信息+“上拉加载图文详情”】
        }
        rows = rows + _leftNameArrs.count;
        return rows;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger rows = _tagArrs.count;
    if (indexPath.section == 0) {
        ProductDetailImgCell *cell = [ProductDetailImgCell cellWithTableView:tableView];
        [cell spec_setupProductDetailImgCell:aLcProducct currentSpecIndex:_currentSpecIndex];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1){
        for (int i = 0; i<rows; i++) {
            if (indexPath.row == i) {
                ProDetailTagCell *cell = [ProDetailTagCell cellWithTableView:tableView];
                NSArray *tags = _tagArrs[i];
                NSString *leftName = _leftNameArrs[i];
                NSString *selectedStr = _selectedTagArrs[indexPath.row];
                [cell setupProDetailTagCellData:leftName indexRow:indexPath.row andTags:tags andSelectedIndex:selectedStr];
                cell.ProDetailTagCellBlcok = ^(NSInteger specIndex){
                    [_selectedTagArrs replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%ld",(long)specIndex]];
                    if (_hasSpec && indexPath.row == 0) { //有多规格，并且第一行
                        _currentSpecIndex = specIndex;
                    }
                    [pdTableView reloadData];
                    
                };
                return cell;
            }
            
        }

        if(indexPath.row == rows){
            ProDetailMessageCell *cell = [ProDetailMessageCell cellWithTableView:tableView];
            [cell setupProDetailMessageCellData:aLcProducct];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }else if (indexPath.row == rows+1){
            static NSString *identifier = @"lcidentifier2";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                
            }
            for (UIView *subV in cell.contentView.subviews) {
                if (subV.tag == 1111) {
                    [subV removeFromSuperview];
                }
            }
            cell.contentView.backgroundColor = BackColor;
            UILabel *headLabel1 = [[UILabel alloc]init];
            headLabel1.text = @"^上拉加载图文详情";
            headLabel1.tag = 1111;
            headLabel1.font = [UIFont systemFontOfSize:11];
            CGSize size = [headLabel1.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:headLabel1.font,NSFontAttributeName, nil]];
            headLabel1.frame = CGRectMake((ScreenWidth - size.width)/2, 0, size.width, 30);
            headLabel1.textColor = SetColor(153, 153, 153, 1);
            headLabel1.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:headLabel1];
            UIView *lineView3 = [[UIView alloc] initWithFrame:CGRectMake(headLabel1.frame.origin.x - 80 -10, 15, 80, 1)];
            lineView3.tag = 1111;
            UIView *lineView4 = [[UIView alloc] initWithFrame:CGRectMake(headLabel1.frame.origin.x + size.width + 10, 15, 80, 1)];
            lineView3.backgroundColor = SetColor(204, 204, 204, 0.6);
            lineView4.backgroundColor = SetColor(204, 204, 204, 0.6);
            lineView4.tag = 1111;
            [cell.contentView addSubview:lineView3];
            [cell.contentView addSubview:lineView4];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        }
    }

    
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //多规格的话，默认显示第一种的
    
    LCProductSpec *aSpec = [[LCProductSpec alloc]init];
    if (aLcProducct.productspec.count > _currentSpecIndex) {
        aSpec = aLcProducct.productspec[_currentSpecIndex];
    }
    NSString *specValueStr = @"";
    if (aSpec.specname.length > 0 ) {
        specValueStr = aSpec.specname;
    }
    NSString *introductStr = @"";
    if (aLcProducct.sdescription.length > 0) {
        introductStr = aLcProducct.sdescription;
    }
    if (indexPath.section == 0) {
        CGFloat rowH = 0;
        rowH = ScreenWidth+15+[self getHeight:aLcProducct.productname fontSize:16 strwidth:ScreenWidth-20]+8+20+10;
        return rowH+5; //5为第一个cell中间的高
    }else{
        for (int i = 0; i<_tagArrs.count; i++) {
            if (indexPath.row == i) {
                NSArray *tags = _tagArrs[i];
                CGFloat tagH = [self getHeightTagCell:tags andLeftName:_leftNameArrs[i]];
                if (tagH+0.5 > 44.5) {
                }else{
                    tagH = 44.5;
                }
                return tagH;
            }
        }
        if (indexPath.row == _tagArrs.count) {
            if (aLcProducct.productspec.count > 1) {//有规格标签，就不要此处的规格
                CGFloat introductHH = [self getMessageHeight:introductStr];
                return 10+14+10+introductHH+10;
            }else{
                CGFloat guigeHH = [self getMessageHeight:specValueStr];
                CGFloat introductHH = [self getMessageHeight:introductStr];
                return 10+14+10+guigeHH+10+introductHH+10;
            }
            
        }else if (indexPath.row == _tagArrs.count+1){
            return 30.0;
        }
    }
    return 0.00001;
}
-(CGFloat)getMessageHeight:(NSString *)mess
{
    NSMutableAttributedString *introText = [[NSMutableAttributedString alloc] initWithString:mess];
    introText.yy_font = FontSet(13);
    introText.yy_lineSpacing = 8;
    CGSize introSize = CGSizeMake(ScreenWidth-100, CGFLOAT_MAX);
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:introSize text:introText];
    CGFloat introHeight = layout.textBoundingSize.height;
    return introHeight;
}
-(CGFloat)getHeight:(NSString *)str fontSize:(CGFloat)fontSize strwidth:(CGFloat)strwidth{
    CGSize aSize = [str boundingRectWithSize:CGSizeMake(strwidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return aSize.height;
}


-(CGFloat)getHeightTagCell:(NSArray *)tags andLeftName:(NSString *)leftName
{
    CGFloat leftW =12 + [Utils calculateSizeWithText:leftName height:44 fontSize:12].width;
    SFTagView *tagView = [[SFTagView alloc] initWithFrame:CGRectMake(leftW, 0, ScreenWidth-leftW-12, 44)];
    // alignment 0 左对齐布局 1 右对齐布局
    tagView.alignment = 0;
    tagView.margin    = UIEdgeInsetsMake(9, 0, 9, 0); //整体
    tagView.insets    = 10; //左右间距
    tagView.lineSpace = 9; //上下间距
    for (int j = 0; j<tags.count; j++) {
        SFTag *tag = [SFTag tagWithText:tags[j]];
        tag.cornerRadius = 12;
        tag.borderWidth = 1;
        tag.font = FontSet(13);
        tag.leftRightMargin = 12;
        tag.topBottomMargin = 4;
        [tagView addTag:tag];
        //            NSLog(@"tagView frame: %@", NSStringFromCGRect(tagView.frame));
        
    }
    return tagView.height;
}

#pragma mark -- BackBtnClick
- (void)backAction:(UIButton *)btn {//保存按钮修改
    [self postRefreshNotificationWithDeleteStr:@"NO"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)postRefreshNotificationWithDeleteStr:(NSString *)isDelete
{
    NSMutableDictionary *infoDic = [[NSMutableDictionary alloc] init];
    if (aLcProducct.ispublic.length == 0) {
        aLcProducct.ispublic = @"";
    }
    [infoDic setObject:aLcProducct.ispublic forKey:@"ispublic"];
    if (aLcProducct.ishot.length == 0) {
        aLcProducct.ishot = @"";
    }
    [infoDic setObject:aLcProducct.ishot forKey:@"ishot"];
    
    [infoDic setObject:isDelete forKey:@"isdelete"];
    [infoDic setObject:[NSNumber numberWithInteger:self.CPage] forKey:@"pageIndex"];
    if (self.isSearchVC.length == 0) {
        self.isSearchVC = @"";
    }
    [infoDic setObject:self.isSearchVC forKey:@"isSearchVC"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LC_productManager_refresh object:infoDic];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [MBProgressHUD showLCHud:self.view];
        NSString *url = [NSString stringWithFormat:deleteProductUrl,[AppData share].username,[AppData share].username,aLcProducct.productid];
        [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *result = [dic objectForKey:@"m"];
            if ([result isEqualToString:@"success"]) {
                [MBProgressHUD hideLCHud:self.view];
                [[MessShowView share]showWithMess:@"商品删除成功" login:YES];
                [self postRefreshNotificationWithDeleteStr:@"YES"];
                [self.navigationController popViewControllerAnimated:YES];

                
            }else  {
                [MBProgressHUD hideLCHud:self.view];
                [[MessShowView share]showWithMess:result login:NO];
            }
        }];
    }else {
        
    }
}

@end
